package com.example.client_fmf;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Socket;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.util.Log;



public class Connection implements Closeable, Serializable {

    public static final String LOG_TAG = "Traccar.Connection";
//    public static final int SOCKET_TIMEOUT = 10 * 1000;
    public static AsyncResponse delegate=null;
    /**
     * Callback interface
     */


    private  Socket socket;
    private static OutputStream socketStream;
    private static InputStream socketInputStream ;
    
    private static boolean closed = true;
    private static boolean busy;

    public boolean isClosed() {
        return closed;
    }

    public boolean isBusy() {
        return busy;
    }



    public Connection() {
       
        closed = false;
        busy = false;
    }
	@SuppressLint("NewApi")
	public void connect(final String address, final int port) {
//        busy = true;
		
        new AsyncTask<Void, Void, Boolean>() {

            @Override
            protected Boolean doInBackground(Void... params) {
                try {
                    socket = new Socket();
                    socket.connect(new InetSocketAddress(address, port));
                    
//                    socket.setSoTimeout(SOCKET_TIMEOUT);
                    socketStream = socket.getOutputStream();
                    socketInputStream = socket.getInputStream();
                    return true;
                } catch (Exception e) {
                    Log.w(LOG_TAG, e.getMessage());
                    return false;
                }
            }

            @Override
            protected void onCancelled() {
                if (!closed) {
                    busy = false;
                    //handler.onConnected(false);
                }
            }

            @Override
            protected void onPostExecute(Boolean result) {
                if (!closed) {
                    busy = false;
                  //  handler.onConnected(result);
                }
            }

        }.execute();

    }
	 public static void send(String message) throws UnsupportedEncodingException {
	   
		 busy = true;
	       
	        new AsyncTask<String, Void, Object>() {

	            @Override
	            protected Object doInBackground(String... params) {
	                try {
	                     
	                	socketStream.write(params[0].getBytes());
	                    socketStream.flush();
	                    byte []data = new byte[100] ;
	                    String res_msg  =""  ; 
	                    int a = socketInputStream.read(data)   ; 
	                    //startReceiving() ; 
	                    
	                    return data ; 

	                } catch (Exception e) {
	                    Log.w(LOG_TAG, e.getMessage());
	                    return e;
	                }
	            }

	            @Override
	            protected void onCancelled() {
	                if (!closed) {
	                    busy = false;
	                  //  handler.onSent(false);
	                }
	            }

	            @Override
	            protected void onPostExecute(Object result) {
	                if (!closed) {
	                	byte[] b = (byte[]) result ; 
	                	String s = "?"; 
	                	try {
							 	s = new String(b, "UTF-8") ;
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} 
	                	delegate.processFinish(s);
	                	
	                    busy = false;
	                   // handler.onSent(result);
	                }
	            }

	        }.execute(message);
	  
	       
	    }

        public void recieve() {
            busy = true;
            
            new AsyncTask<String, Void, Object>() {

            	 @Override
                protected Object doInBackground(String...strings) {
                    try {
                    	byte []data = new byte[100] ; 
                    	
                    	socketInputStream.read(data) ; 
                    	
                        return data;
                        
                    } catch (Exception e) {
                        Log.w(LOG_TAG, e.getMessage());
                        return e;
                    }
                }

                @Override
                protected void onCancelled() {
                    if (!closed) {
                        busy = false;
                      //  handler.onSent(false);
                    }
                }

                @Override
                protected void onPostExecute(Object result) {
                	if (!closed) {
	                	byte[] b = (byte[]) result ; 
	                	String s = "?"; 
	                	try {
							 	s = new String(b, "UTF-8") ;
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} 
	                //	delegate.processFinish(s);
	                	
	                    busy = false;
	                   // handler.onSent(result);
	                }
                }

				

            }.execute();
//            return data ; 

    }
    
//        public void startReceiving()
//        {
//        	Runnable r = new RecieverThread(socket, delegate);
//    		new Thread(r).start();
//        }
    @Override
    public void close() {
        closed = true;
        try {
            if (socketStream != null) {
                socketStream.close();
            }
            if (socketInputStream != null) {
            	socketInputStream.close();
            }
            if (socket != null) {
                socket.close();
            }
        } catch (Exception e) {
            Log.e(LOG_TAG, e.getMessage());
        }
    }

	

}
